import { lazyReportBatch } from "../report";

//监听浏览器中发生的各种性能事件（Performance Entries），这些事件包含了网页加载过程中的关键性能数据
export default function observerEntries():void{
    //loading（DOM还未完全解析完成）——>interactive(文档解析完成，子资源还未加载完成)——
    if(document.readyState==="complete"){
        observeEvent();        
    }else{
        const onLoad=()=>{
            observeEvent();
            window.removeEventListener("load",onLoad,true);
        }
        window.addEventListener("load",onLoad,true);
    }
}
export function observeEvent():void{
    const type="resource";
    const entryHandler=(list:PerformanceObserverEntryList,observer:PerformanceObserver):void=>{
        const data=list.getEntries();
        for(const entry of data){ 
            observer && observer.disconnect();
            
            // Cast to PerformanceResourceTiming to access resource-specific properties
            const resourceEntry = entry as PerformanceResourceTiming;
            
            const reportData = {
                name: entry.name, // 资源的名字
                type: 'performance', // 类型
                subType: entry.entryType, //类型
                sourceType: resourceEntry.initiatorType, // 资源类型
                duration: entry.duration, // 加载时间
                dns: resourceEntry.domainLookupEnd - resourceEntry.domainLookupStart, // dns解析时间
                tcp: resourceEntry.connectEnd - resourceEntry.connectStart, // tcp连接时间
                redirect: resourceEntry.redirectEnd - resourceEntry.redirectStart, // 重定向时间
                ttfb: resourceEntry.responseStart, // 首字节时间
                protocol: resourceEntry.nextHopProtocol, // 请求协议
                responseBodySize: resourceEntry.encodedBodySize, // 响应内容大小
                responseHeaderSize: resourceEntry.transferSize - resourceEntry.encodedBodySize, // 响应头部大小
                transferSize: resourceEntry.transferSize, // 请求内容大小
                resourceSize: resourceEntry.decodedBodySize, // 资源解压后的大小
                startTime: performance.now(),
            };
            console.log(reportData);
            // TODO:发送数据
            //lazyReportBatch( reportData);

        }  
    }
    const observer=new PerformanceObserver(entryHandler);
    observer.observe({type:type,buffered:true})
}